package com.lanp.springsd.config.database;

import com.lanp.springsd.common.DataSourceCSV;

/**
 * @author jiangpeng
 * Created with IntelliJ IDEA.
 * Description:  动态数据源上下文
 * Date: 2022-03-04 16:20:10
 */
public class RoutingDataSourceContext implements AutoCloseable {
    /**
     * 线程上下文的数据源路由key
     */
    static final ThreadLocal<String> threadLocalDataSourceKey = new ThreadLocal<>();

    /**
     * 获取当前数据源路由
     *
     * @return
     */
    public static String getDataSourceRoutingKey() {
        String key = threadLocalDataSourceKey.get();
        return key == null ? DataSourceCSV.masterDataSource : key;
    }

    /**
     * 设置当前数据源路由
     *
     * @return
     */
    public RoutingDataSourceContext(String key) {
        threadLocalDataSourceKey.set(key);
    }

    @Override
    public void close() throws Exception {
        System.out.println("调用关闭清空数据源路由");
        threadLocalDataSourceKey.remove();
    }
}
